/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import BUS.*;
import DAO.*;
import DTO.*;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import quanlyduongsat.*;
/**
 *
 * @author Phong
 */
public class DangNhapForm extends javax.swing.JFrame {
    private int UTF;

    /**
     * Creates new form QuanLyNhaHangForm
     */
    public DangNhapForm() throws IOException {
        initComponents();
        load();
    }
public void load () throws FileNotFoundException, IOException
{
   
    if(jCheckBox1.isSelected()){
         Scanner in=new Scanner(new FileInputStream("data.txt"));
        PrintWriter out=new PrintWriter(new FileOutputStream("out.txt"));
        txtTaiKhoan.setText(in.nextLine());
        while(in.hasNextLine()){
            txtMatKhau.setText(in.nextLine());
        }
        in.close();
        out.close();
    }
}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtTaiKhoan = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtMatKhau = new javax.swing.JPasswordField();
        btnDangNhap = new javax.swing.JButton();
        btnThoat = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Đăng Nhập"));

        jLabel1.setText("Tên Đăng Nhập:");

        jLabel2.setText("Password:");

        btnDangNhap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/key.png"))); // NOI18N
        btnDangNhap.setText("Đăng Nhập");
        btnDangNhap.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDangNhapActionPerformed(evt);
            }
        });

        btnThoat.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/logout.png"))); // NOI18N
        btnThoat.setText("Thoát");
        btnThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThoatActionPerformed(evt);
            }
        });

        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Nhớ Mật Khẩu");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtMatKhau)
                    .addComponent(txtTaiKhoan)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnDangNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jCheckBox1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnThoat, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)))
                .addContainerGap(42, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtTaiKhoan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDangNhap)
                    .addComponent(btnThoat))
                .addGap(18, 18, 18)
                .addComponent(jCheckBox1)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents
  public static int KiemTraDangNhap(String ten, String ma){
        try{
            ArrayList dsma = new ArrayList();
            Connection con=DBConnect.Connect();
            
           // String sql="SELECT MaMonAn, TenMonAn,MaQuocGia,MaNguyenVatLieu from MonAn";
            String sql = String.format ("SELECT  * from User where Username='%s' and Password='%s'", ten, ma);      
            Statement st=con.createStatement();
            
            ResultSet rs=st.executeQuery(sql);
            
          //  int rs=st.executeUpdate(sql);
            int kq=0;
          //  kq=rs.getRow();
             while(rs.next()){
                 kq++;
//                String yy;
//                yy= rs.getString("Username");
//                 JOptionPane.showMessageDialog(null,yy, " Thông Tin :" + "Cần Biết", JOptionPane.INFORMATION_MESSAGE); 
             }
            con.close();
             return  kq;
            
        }catch(Exception ex){
             System.out.println(ex.getMessage());
            return 0;
        }
    }
      public void close(){
        WindowEvent winClosingEvent = new WindowEvent(this,WindowEvent.WINDOW_CLOS­ING);
        Toolkit.getDefaultToolkit().getSystemEve­ntQueue().postEvent(winClosingEvent);

}
      public void ghifile() throws FileNotFoundException, IOException
      {
          FileOutputStream out=new FileOutputStream("data.txt");
        PrintWriter output=new PrintWriter(out,true);
        output.println(txtTaiKhoan.getText());
        output.println(txtMatKhau.getText());
        out.close();
        output.close();
//      FileOutputStream fos=new FileOutputStream("data.txt",true);
//     PrintWriter pw = new PrintWriter(fos);
//     pw.println(txtTaiKhoan.getText());
//     pw.println(txtMatKhau.getText());
//     fos.flush();
//     fos.close();
      }
    private void btnDangNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDangNhapActionPerformed
  
//        this.hide();
////        UserList us=new UserList();
//        us=XuLyLinhTinhBUS.DangNhap("admin","123");  
//        MainProgram main = new MainProgram(us);
//        main.setVisible(true);
//        this.dispose();       
   
         if (txtTaiKhoan.getText().isEmpty() || String.valueOf(txtMatKhau.getPassword()).isEmpty())
        {
            
                 ShakingFrame s = new ShakingFrame(this);
                 s.startShake();
                 JOptionPane.showMessageDialog(this, "Chưa nhập đầy đủ thông tin");
            return;
        }
        
        String TaiKhoan = txtTaiKhoan.getText();
        String MatKhau = String.valueOf(txtMatKhau.getPassword());
        UserList us=new UserList();
        us=XuLyLinhTinhBUS.DangNhap(TaiKhoan,MatKhau);
        
        if (us.UserName != "")
        {
     
            JOptionPane.showMessageDialog(this, "Đăng Nhập Thành Công !", "Xác nhận ", JOptionPane.INFORMATION_MESSAGE);
            if(jCheckBox1.isSelected())
            {
                try {
                    ghifile();
                } catch (IOException ex) {
                    Logger.getLogger(DangNhapForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            else
            {
                try{
                 FileOutputStream out=new FileOutputStream("data.txt");
        PrintWriter output=new PrintWriter(out,true);
        output.println("");
        output.println("");
        out.close();
        output.close();
                }catch (IOException ex) {
                    Logger.getLogger(DangNhapForm.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
            MainProgram main = new MainProgram(us);
            main.setVisible(true);
            this.dispose();
        }
        else
        {
            ShakingFrame s = new ShakingFrame(this);
            s.startShake();
            JOptionPane.showMessageDialog(this, "Thông tin tài khoản, mật khẩu không đúng");
    }
    }//GEN-LAST:event_btnDangNhapActionPerformed

    private void btnThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThoatActionPerformed
      
                 ShakingFrame s = new ShakingFrame(this);
                 s.startShake();
//        if (JOptionPane.showConfirmDialog(this, "Bạn muốn đóng ứng dụng này ?", "Xác nhận đóng", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
//            System.exit(1);
//        }
    }//GEN-LAST:event_btnThoatActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DangNhapForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DangNhapForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DangNhapForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DangNhapForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new DangNhapForm().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(DangNhapForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDangNhap;
    private javax.swing.JButton btnThoat;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField txtMatKhau;
    private javax.swing.JTextField txtTaiKhoan;
    // End of variables declaration//GEN-END:variables
}
